package com.intelligentmeterreadingsys.otherequipment.activity;

import com.android.rfid.RfidHelper;
import com.intelligentmeterreadingsys.R;
import com.intelligentmeterreadingsys.otherequipment.db.EquipementDao;
import com.intelligentmeterreadingsys.povo.OtherEquipmentPOVO;
import com.intelligentmeterreadingsys.util.BluetoothHelp;
import com.intelligentmeterreadingsys.util.TipHelper;
import com.intelligentmeterreadingsys.waterlist.copywater.activity.ImageSwitcherActivity;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

/**
 * RFID读卡正常设备巡检
 * 
 * @author king
 * 
 */
public class EquipementRfidCheckActivity extends Activity implements OnClickListener {
	public static final int ITEM0 = Menu.FIRST;// 系统值
	private final static int DIALOG = 1;
	public int RFIDtype = 2;// RFID协议
	public String xieyi = "15693";
	public RfidHelper rh;// 读卡帮助对象
	public ProgressDialog pd;// 读卡进度条
	public boolean isStop = true;
	public boolean issave = false;
	public BluetoothHelp bluehelp;
	public long time;
	public boolean isupload = false;
	public String readtype = "终端读卡";
	public String[] readdate;
	public OtherEquipmentPOVO eq=null;
	public TextView textview1;// 设备编号
	public TextView textview2;// 设备类型
	public TextView textview3;// 安装时间
	public TextView textview4;// 安装地址
	public TextView textview5;// 上次巡检日期
	public TextView textview6;// 上次巡检结果
	public Spinner spinner;// 设备状态
	public EditText edit;// 巡检结果
	public Button button1;// 拍照
	public Button button2;// 保存
	public Button button3;// 上传
    public String RfidNumber="";
    public String checktype="正常";
    public String[] date=new String[]{"正常","异常"};
    private static final int REQUEST_CODE_TAKE_IMAGE = 1;
	public String locationtype = "gps";
	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.other_equipment_check);
		init();
		Toast.makeText(this, "正在读卡中，请将手持终端靠近设备", Toast.LENGTH_SHORT).show();
		time=System.currentTimeMillis();
		myThread.start();
	}

	/**
	 * 初始化控件
	 */
	public void init() {
		textview1 = (TextView) findViewById(R.id.other_equipment_check_number);
		textview2 = (TextView) findViewById(R.id.other_equipment_check_type);
		textview3 = (TextView) findViewById(R.id.other_equipment_check_date);
		textview4 = (TextView) findViewById(R.id.other_equipment_check_adds);
		textview5 = (TextView) findViewById(R.id.other_equipment_check_lastcheckdate);
		textview6 = (TextView) findViewById(R.id.other_equipment_check_lastcheckresult);
		button1 = (Button) findViewById(R.id.other_equipment_check_paizhao);
		button2 = (Button) findViewById(R.id.other_equipment_check_save);
		button3 = (Button) findViewById(R.id.other_equipment_check_upload);
		spinner = (Spinner) findViewById(R.id.other_equipment_check_equipmentstatus);
		edit = (EditText) findViewById(R.id.other_equipment_check_thisequipmentresult);
		button1.setOnClickListener(this);
		button2.setOnClickListener(this);
		button3.setOnClickListener(this);
	   ArrayAdapter<String> ada1=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,date);//放数据
	   ada1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);//设置打开方式
       spinner.setAdapter(ada1);
       
       spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

		@Override
		public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			checktype=arg0.getItemAtPosition(arg2).toString();
			
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
		      
		}
	});
        initRFID(RFIDtype);
       bluehelp=new BluetoothHelp(this);
       bluehelp.init();
       
	}
     
	/**
	 * 读卡消息类
	 */
	Handler readCard=new Handler(){

		@Override
		public void handleMessage(Message msg) {
            long times=System.currentTimeMillis();
            if(times-time>120000){
            	isStop=false;
            	if(readtype.equals("手持终端")){
            		pd.dismiss();
            	}else{
            	    bluehelp.close();
            	}           	
            	Toast.makeText(EquipementRfidCheckActivity.this, "读卡超时",
						Toast.LENGTH_LONG).show();	
            	
            	return;
            }
			if (msg.what == 1) {
				isStop=false;
				if(readtype.equals("手持终端")){
            		pd.dismiss();
            	}else{
            	    bluehelp.close();
            	}
				Toast.makeText(EquipementRfidCheckActivity.this,
						"读卡成功" + msg.obj.toString(), Toast.LENGTH_LONG).show();
				
				EquipementDao dao=new EquipementDao(EquipementRfidCheckActivity.this);				
				 eq=dao.queryCheckEquipment(null, msg.obj.toString());
				dao.close();			
				if(eq==null){
					Toast.makeText(EquipementRfidCheckActivity.this, "此RFID卡还未绑定设备", Toast.LENGTH_LONG).show();
					return;
				}
				viewdate();
				TipHelper.Vibrate(EquipementRfidCheckActivity.this, 1000);				
			} 
		}
	};
	
	/**
	 * 读卡线程
	 */
	Thread myThread=new Thread(){

		@Override
		public void run() {

			while (isStop) {
				String id=RfidNumber = "";
				if(readtype.equals("终端读卡")){	
				  id=RfidNumber = rh.readIDString();
					
				}else{
					
					 id=RfidNumber=bluehelp.getRfidId();
				}			
				
				if (!TextUtils.isEmpty(id)) {
					
					Message msg = readCard.obtainMessage();
					msg.what = 1;
					msg.obj = id;
					readCard.sendMessage(msg);
				}
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
		
			super.run();
		}
		
	};
	
	/**
	 * 展现数据
	 */
	public void viewdate(){
		textview1.setText("");
		textview2.setText("");
		textview3.setText("");
		textview4.setText("");
		textview5.setText("");
		textview6.setText("");
		edit.setText("");
		if(eq!=null){
			textview1.setText(eq.getNumber());
			textview2.setText(eq.getTypename());
			textview3.setText(eq.getDate());
			textview4.setText(eq.getAdds());
			textview5.setText(eq.getLastcheckdate());
			textview6.setText(eq.getLastcheckresult());
			edit.setText(eq.getCheckdesc());
			if(eq.getChecktype()!=null){
				if(eq.getChecktype().equals("正常")){
					spinner.setSelection(0, true);
				}else{
					spinner.setSelection(1, true);
				}
				
			}
			
			
		}
	}

	@Override
	public void onClick(View v) {
		Intent intent=null;
		if(eq==null){
			Toast.makeText(EquipementRfidCheckActivity.this, "没有找到设备不能进行此操作", Toast.LENGTH_SHORT).show();
			return;
		}
		switch (v.getId()) {
		case R.id.other_equipment_check_paizhao:
			 intent=new Intent(this, ImageSwitcherActivity.class);
			 Bundle bundle=new Bundle();
			 bundle.putString("otherid", eq.getId());
			 bundle.putString("status", "5");
			 bundle.putString("classname", "EquipementRfidCheckActivity");
			 intent.putExtras(bundle);
			 startActivity(intent);
			break;
		case R.id.other_equipment_check_save:
			  EquipementDao dao=new EquipementDao(this);
			issave= dao.checkEquipement(checktype, edit.getEditableText().toString(), eq.getId(),"0");
			if(issave){
				Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
			}else{
				Toast.makeText(this, "保存失败", Toast.LENGTH_SHORT).show();
			}
			break;
		case R.id.other_equipment_check_upload:
			 
			break;
		default:
			break;
		}
		
	}
	
	
		
	
	
	/**
	 * 上传消息类
	 */
	Handler uploadHandler=new Handler(){

		@Override
		public void handleMessage(Message msg) {
			
		}
		
	};
	@Override
	protected void onDestroy() {
		 if(rh != null){
			    isStop=false;
				rh.stopAutoRead();
			    rh.close();
			}
		 if(bluehelp!=null){
			 bluehelp.stop();
		 }
		 
		
		super.onDestroy();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, ITEM0 + 1, 0, "拍照");
	
		menu.add(0, ITEM0 + 3, 0, "读卡协议");
		menu.add(0, ITEM0 + 4, 0, "读卡方式");
		menu.findItem(ITEM0 + 1);
		return super.onCreateOptionsMenu(menu);
	}
	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog dialog = null;
		switch (id) {

		
	
		case DIALOG + 2:
			AlertDialog.Builder	builder = new android.app.AlertDialog.Builder(this);
			// 设置对话框的图标
			builder.setIcon(R.drawable.buttondraw);
			// 设置对话框的标题
			builder.setTitle("单选按钮对话框");
			// 0: 默认第一个单选按钮被选中

			builder.setSingleChoiceItems(R.array.hobby, 0,
					new android.content.DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							xieyi = getResources()
									.getStringArray(R.array.hobby)[which];

						}
					});

			// 添加一个确定按钮
			builder.setPositiveButton(" 确 定 ",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							if (xieyi.equals("15693")) {
								time = System.currentTimeMillis();
								RFIDtype=2;
								initRFID(2);
							} else if (xieyi.equals("14443")) {
								time = System.currentTimeMillis();
								RFIDtype=1;
								initRFID(1);
							}
						}
					});
			// 创建一个单选按钮对话框
			dialog = builder.create();
			break;
		case DIALOG + 3:
			if (readtype.equals("终端读卡")) {
				readdate = new String[] { "终端读卡", "蓝牙读卡" };
			} else {
				readdate = new String[] { "蓝牙读卡", "终端读卡" };
			}

			builder = new android.app.AlertDialog.Builder(this);
			// 设置对话框的图标
			builder.setIcon(R.drawable.buttondraw);
			// 设置对话框的标题
			builder.setTitle("读卡方式选择");
			// 0: 默认第一个单选按钮被选中

			builder.setSingleChoiceItems(readdate, 0,
					new android.content.DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							readtype = readdate[which];

						}
					});

			// 添加一个确定按钮
			builder.setPositiveButton(" 确 定 ",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							time = System.currentTimeMillis();
							if(readtype.equals("终端读卡")){
								bluehelp.start();
							}else{
								initRFID(RFIDtype);
							}
							
						}
					});
			// 创建一个单选按钮对话框
			dialog = builder.create();
			break;
		}

		return dialog;
	}

	/**
	 * 初始化读卡
	 */
	public void initRFID(int type) {
		rh = RfidHelper.getInstance();
		rh.setCardType(type);
		rh.open();
		rh.setAllNoOfTimes(1);
		rh.setTimeInterval(50);
		// 设置激活读卡器后等待的时间.sdk默认10
		rh.setPingTimeInterval(10);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if(item.getItemId()==(ITEM0+1)){
			if(eq!=null){
				Intent intent=new Intent(this, EquipementCheckUploadActivity.class);
				Bundle bundle = new Bundle();
				bundle.putString("status", "4");
				bundle.putString("classname", "EquipementCheckUploadActivity");
				bundle.putString("other", eq.getId());
				startActivity(intent);
			}
			
		}else if(item.getItemId()==(ITEM0+3)){
			showDialog(DIALOG+2);
		}else if(item.getItemId()==(ITEM0+4)){
			showDialog(DIALOG+3);
		}
		return super.onOptionsItemSelected(item);
	}

	
}
